package entity.model.relationships;

import entity.model.Entity;
import entity.model.EntityModel;

import java.lang.reflect.Field;

public class RelationshipFactory {

    public static void create(Entity entity, Field field) {

        Entity owner = EntityModel.INSTANCE.ENTITY_MAP.get(field.getType());

        if (field.isAnnotationPresent(entity.model.annotations.ManyToMany.class)) {
            Class<?> possessionType = field.getAnnotation(entity.model.annotations.ManyToMany.class).type();
            if (EntityModel.INSTANCE.ENTITY_MAP.containsKey(possessionType))
                createManyToMany(owner, possessionType, field, entity);
            else
                EntityModel.INSTANCE.on(possessionType, () -> createManyToMany(owner, possessionType, field, entity));
        }
        else
        {
            Relationship relationship;

            if (field.isAnnotationPresent(entity.model.annotations.OneToOne.class))
                relationship = new OneToOne(owner, entity, field);
            else
                relationship = new OneToMany(owner, entity, field);

            entity.getRelationships().add(relationship);
            System.out.println(entity.getName() + ", " + field.getName() + ", " + relationship);

        }
    }

    private static void createManyToMany(Entity owner, Class<?> possessionType, Field field, Entity entity) {
        Entity possession = EntityModel.INSTANCE.ENTITY_MAP.get(possessionType);
        ManyToMany relationship = new ManyToMany(owner, possession, field, entity);
        entity.getRelationships().add(relationship);
        System.out.println(entity.getName() + ", " + field.getName() + ", " + relationship);
    }
}
